package com.atguigu.cf.test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;

/**
 * author: 封捷
 * date: 2023/1/29 16:50
 * version: 1.0
 */
public class Demo06TaskResult {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = ThreadPoolProvider.getThreadPool();

        // 封装任务，返回 CompletableFuture 对象
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "task result very happy");

        // 以同步方式获取任务结果：main 线程会阻塞直到目标任务完成，返回结果
        String taskResultBySyncWay = future.get();
        System.out.println("taskResultBySyncWay = " + taskResultBySyncWay);

        // 以异步回调方式获取任务结果：main 线程调用 whenComplete() 执行设定，然后 main 线程就可以去执行后续代码，不需要等待接收返回值的方法被调用
        future.whenComplete((taskResultByAsyncWay, throwable) -> {
            System.out.println("taskResultByAsyncWay = " + taskResultByAsyncWay);
        });

    }

}
